package com.edu.gdkm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.edu.gdkm.dao.dypDao;
import com.edu.gdkm.util.cookiesUtil;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {

    private dypDao dao = null;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        cookiesUtil util = new cookiesUtil();

        // 获取用户 and 密码
        String user = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        // 多选框获取
        String autoLogin = req.getParameter("auto_login");
        String autoPwd = req.getParameter("auto_pwd");
        try {
            // 获取数据库
            dao = new dypDao();
            // 字符串拼接
            String call = String.join(",", dao.str(user), dao.str(pwd));
            /* 用户登录判断 */
            if (isLogin(    // 判断返还值是否为 “true”
                    dao.selectStor("user_login", call))){
                String cid = dao.resultFirst(
                        dao.select("cid", "customer",
                                "cname="+dao.str(user)));// 用户 ID
                String cookVal = String.join("&", user, cid);
                // 添加自定义 Cookies
                resp.addCookie(
                        util.crateCookie("dyp_user", cookVal, 24));
                // 转发 => 电影详情
                resp.sendRedirect(req.getContextPath()+"/filmListServlet");
                return;
            }
            /* 管理员登录 */
            if (isLogin(    // 判断返还值是否为 “true”
                    dao.selectStor("admin_login", call))){
                String aid = dao.resultFirst(dao.select("aid", "category", "aname="+dao.str(user)));
                String cookVal = String.join("&", user, aid);
                // 添加自定义 Cookies
                resp.addCookie(
                        util.crateCookie("dyp_user", cookVal, 24));
                // 转发 => 后台管理系统
                resp.sendRedirect(req.getContextPath() + "/adminServlet");
                return;
            }
            // 关闭
            dao.close();
            // 登录失败 -> 转发 => 登录页
            resp.sendRedirect("/dyp/index.html");
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isLogin(ResultSet result) throws SQLException {
        return (dao.resultFirst(result).equals("true"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
